<template>
  <view class="bidBuy-view">
    <view class="goods-img">
      <image v-if="goodsDetail.morebagPublishPictures" :src="goodsDetail.morebagPublishPictures[0].picture" mode="aspectFit"></image>
    </view>
    <view class="downTime" v-if="current == 0 && timer">
      {{$t("bidBuy.downTime")}}：{{d>0?d+$t("bidBuy.day"):""}}    {{h ? h + ":" : ""}}{{m ? m + ":" : ""}}{{s?s:""}}
    </view>
    <view class="layout">
      <view class="price">
        <view class="name">
          {{$t("goodsReleased.language") == "zh"?goodsDetail.commodity:goodsDetail.commodityEn}}
        </view>
      </view>
      <view class="commodity-info">
        <!-- <view class="titleGoods">{{$t("commDetail.detail")}}</view> -->

        <view class="commodity-text temp">
          <view class="ls" v-if="condition.length > 0">
            {{$t("language") == "zh"?condition[0].parentName:condition[0].parentEndName}}:  <text
              class="bd" style="margin-left: 10rpx;text-transform: none;">{{$t("language") == "zh"?condition[0].brandName:condition[0].brandEngName?condition[0].brandEngName:condition[0].brandName}}</text>
          </view>

          <view class="ls">
            <!-- {{$t("commDetail.desc")}}: --> <text
              class="bd no-margin" style="margin-left: 10rpx;text-transform: none;">{{goodsDetail.shopDescribe}}</text>
          </view>

          <view class="ls">
            {{$t("commDetail.sku")}}:  <text
              class="bd" style="margin-left: 10rpx;text-transform: none;">{{goodsDetail.sku}}</text>
          </view>
        </view>

        <view class="commodity-text temp">
          <view class="ls" v-if="addr.length > 0">
            {{$t("language") == "zh"?addr[0].parentName:addr[0].parentEndName}}:  <text
              class="bd" style="margin-left: 10rpx;text-transform: none;">{{$t("language") == "zh"?addr[0].brandName:addr[0].brandEngName?addr[0].brandEngName:condition[0].brandName}}</text>
          </view>
        </view>

        <view class="commodity-text temp">
          <view class="ls" v-if="filterBrand.length > 0">
            {{$t("language") == "zh"?filterBrand[0].parentName:filterBrand[0].parentEndName}}:  <text
              class="bd" style="margin-left: 10rpx;text-transform: none;">{{$t("language") == "zh"?filterBrand[0].brandName:filterBrand[0].brandEngName?filterBrand[0].brandEngName:filterBrand[0].brandName}}</text>
          </view>
          <view class="ls" v-else>
            {{$t("commDetail.brand")}}:  <text
              class="bd" style="margin-left: 10rpx;text-transform: none;color: red;">{{$t("commDetail.none")}}</text>
          </view>
        </view>

        <view class="commodity-text" v-if="goodsDetail.measurement">
          <view class="ls">
            {{$t("goodsReleased.dimensions")}}:
          </view>

          <view class="ls font-col">
            {{$t("commDetail.length")}}: <text
              class="bd" style="margin-left: 10rpx;text-transform: none;">{{goodsDetail.measurement.indexOf("x") === -1?goodsDetail.measurement.split("*")[0]:goodsDetail.measurement.split("x")[0]}}</text>
          </view>
          <view class="ls font-col">
            {{$t("commDetail.width")}}: <text
              class="bd" style="margin-left: 10rpx;text-transform: none;">{{goodsDetail.measurement.indexOf("x") === -1?goodsDetail.measurement.split("*")[1]:goodsDetail.measurement.split("x")[1]}}</text>
          </view>
          <view class="ls font-col">
            {{$t("commDetail.height")}}: <text
              class="bd" style="margin-left: 10rpx;text-transform: none;">{{goodsDetail.measurement.indexOf("x") === -1?goodsDetail.measurement.split("*")[2]:goodsDetail.measurement.split("x")[2]}}</text>
          </view>
        </view>

        <view class="commodity-text temp" v-if="series">
          <view class="ls">
            {{$t("language") == "zh"?series[0].parentName:series[0].parentEndName}}:  <text
              class="bd" style="margin-left: 10rpx;text-transform: none;">{{$t("language") == "zh"?series[0].brandName:series[0].brandEngName?series[0].brandEngName:series[0].brandName}}</text>
          </view>
        </view>

        <view class="commodity-text" v-if="goodsDetail.category">
          <view class="lh plaWid" v-if="item.parentName !== '品类'" v-for="item in goodsDetail.category" :key="item.id">
            {{$t("language") == "zh"?item.parentName:item.parentEndName}}:  <text
              class="bd" style="margin-left: 10rpx;text-transform: none;">{{$t("language") == "zh"?item.brandName:item.brandEngName}}</text>
          </view>
        </view>

        <view class="commodity-text temp" v-if="goodsDetail.productionTime">
          <view class="ls">
            {{$t("goodsReleased.year")}}: <text class="bd"
                                                style="margin-left: 10rpx;text-transform: none;">{{goodsDetail.productionTime}}</text>
          </view>
        </view>
      </view>

      <!-- <view class="bid-buy">
        <view class="bid-buy-btn" :class="{common: current == 0}" @tap="current=0">
          {{$t("bidBuy.seePrice")}}
        </view>
        <view class="bid-buy-btn" :class="{common: current == 1}" @tap="current=1">
          {{$t("bidBuy.nowBuy")}}
        </view>
      </view> -->

      <view class="show-price" v-if="current == 0">
        <text class="show-price-desc" style="margin-right: 10rpx;">
<!--          {{$t("bidBuy.sellPrice")}}:-->
        </text> <text class="show-price-bid">$ {{String(goodsDetail.money).replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')}}</text>
      </view>

      <view class="price-corr" v-if="current == 0">
        <input type="text" v-model="totalPrice" maxlength="7" :placeholder="$t('bidBuy.hint4')" placeholder-style="color:#858585;font-size: 24rpx">
        <view class="pla">
          $
        </view>
        <view class="hintbew" v-if="current == 0">
          {{$t("bidBuy.hint10")}}$&nbsp;{{bidmin.toFixed(2)}}&nbsp;{{$t("bidBuy.hint11")}}$&nbsp;{{goodsDetail.money? String(goodsDetail.money).replace(/(\d)(?=(?:\d{3})+$)/g, '$1')+".00" : "0.00"}}
        </view>
        <view class="hint" v-if="totalPrice < goodsDetail.bidMax">
          {{$t("bidBuy.hint1")}}:
          {{ '$' + String(goodsDetail.bidMax?goodsDetail.bidMax:$t("bidBuy.no")).replace(/\B(?=(\d{3})+(?!\d))/g, ',') }}
        </view>

        <view class="hint" v-else>
          {{$t("bidBuy.hint7")}}
        </view>

        <view class="total-price">
          <text class="total">{{$t("bidBuy.total")}}</text>
          <text class="t-price">$ {{totalPrice ? String(totalPrice).replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')+".00" : "0.00"}}</text>
        </view>

        <!-- <view class="rule">
          {{$t("bidBuy.rule")}}
        </view> -->
      </view>

      <view class="now-buy" v-if="current == 1">
        <!-- <view class="buy-hint">
          {{$t("bidBuy.hint2")}}
        </view> -->
        <view class="goods-price">
          <view class="common-desc">
            {{$t("bidBuy.goodsPrice")}}
          </view>
          <view class="price-g">
            $ {{goodsDetail.money + ".00"}}
          </view>
        </view>
        <!-- <view class="common-desc">
          {{$t("bidBuy.hint3")}}
        </view> -->
      </view>

      <view class="pla-view">

      </view>
    </view>
    <view class="btn">
      <view class="toggleCart" @tap="cancel">{{$t("bidBuy.cancel")}}</view>
      <view class="toggleBuy" @tap="confirm">{{current==0?bidName:$t("bidBuy.confirm1")}}</view>
    </view>

    <u-modal :show="hintShow" confirmColor="#000" :confirmText="confirmText" :cancelText="cancelText" :content='content' @confirm="confirmReceipt" @close="hintShow=false" @cancel="hintShow=false" closeOnClickOverlay showCancelButton></u-modal>
  </view>
</template>

<script>
import { putBidd, getFreightMoney,getAboutUs,getCommDetail,getUserCid,getBid } from "@/common/api.js"

export default {
  data() {
    return {
      current: 0,
      totalPrice: "",
      id: 0,
      goodsDetail: "",
      nowTime: (new Date()).valueOf(),
      d: null,
      h: null,
      m: null,
      s: null,
      timer: null,
      tempTime: 0,
      brokerage: 0,
      freightMoney: 0,
      filterBrand: [],
      series: null,
      condition: [],
      addr: [],
      content: this.$t('bidBuy.hint9'),
      hintShow: false,
      confirmText: this.$t('common.confirm'),
      cancelText: this.$t('common.cancel'),
      isClick: false,
      bidName: "",
      // 售价的85%
      bidmin:0
    }
  },
  methods: {
    getNowTime() {
      const yy = new Date().getFullYear()
      const MM = (new Date().getMonth() + 1) < 10 ? '0' + (new Date().getMonth() + 1) : (new Date().getMonth() + 1)
      const dd = new Date().getDate() < 10 ? '0' + new Date().getDate() : new Date().getDate()
      const HH = new Date().getHours() < 10 ? '0' + new Date().getHours() : new Date().getHours()
      const mm = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes()
      const ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds()
      return yy + '-' + MM + '-' + dd + ' ' + HH + ':' + mm + ':' + ss
    },
    cancel() {
      uni.navigateBack();
    },
    confirmReceipt() {
      uni.navigateTo({
        url: `/pages/confirmGoodsOrder/confirmGoodsOrder?item=${encodeURIComponent(JSON.stringify(this.goodsDetail))}&brokerage=${this.brokerage}&freightMoney=${this.freightMoney}`
      })
      this.hintShow = false;
    },
    async confirm() {
      if (this.current == 0) {
        if (!this.totalPrice) {
          uni.showToast({
            icon: 'none',
            title: this.$t("bidBuy.isIpt"),
            duration: 980
          })
          return
        }

        // if (this.totalPrice < this.goodsDetail.bidMax) {
        // 	uni.showToast({
        // 		icon: 'none',
        // 		title: this.$t("bidBuy.heightPrice"),
        // 		duration: 980
        // 	})
        // 	return
        // }
        // 判断出价价格是否在区间
        if(this.totalPrice<this.bidmin || this.totalPrice > this.goodsDetail.money){
          uni.showToast({
            icon: 'none',
            title:  `${this.$t("bidBuy.hint10")}$ ${this.bidmin.toFixed(2)}${this.$t("bidBuy.hint11")}$ ${this.goodsDetail.money? String(this.goodsDetail.money).replace(/(\d)(?=(?:\d{3})+$)/g, '$1')+".00" : "0.00"}`,
            duration: 980
          })
          return
        }
        const time = this.getNowTime();
        if(this.current == 0) {
          if(this.totalPrice > this.goodsDetail.money) {
            this.hintShow = true;
            return
          }
          if(this.isClick) {
            return
          }
          this.isClick = true;
          const res = await putBidd({commodityId: this.id, bid: this.totalPrice, bidTime: time});
          console.log(res);
          if (res.code === 200) {
            // #ifdef APP
            const resCid = await getUserCid(this.goodsDetail.customerId);
            console.log(resCid);
            uniCloud.callFunction({
              name:"push",
              data:{
                cids:resCid.data.cid,
                title: this.$t('bidBuy.noticeTitle'),
                content: this.$t('bidBuy.noticeContent') + this.goodsDetail.commodity + this.$t('bidBuy.noticeContent2')
              },
              success: (res) => {
                console.log(res);
              },
              fail: (f) => {
                console.log(f);
              }
            })
            // #endif
            this.totalPrice = Number(this.totalPrice);
            console.log(this.totalPrice, this.goodsDetail.money);
            if(this.totalPrice > this.goodsDetail.bidMax) {
              uni.showToast({
                icon: 'none',
                title: this.$t("bidBuy.hint5"),
                duration: 1500,
                fail(res) {
                  console.log(res);
                }
              })
            } else {
              uni.showToast({
                icon: 'none',
                title: this.$t("bidBuy.hint8") + (this.goodsDetail.bidMax - this.totalPrice),
                duration: 1500,
                fail(res) {
                  console.log(res);
                }
              })
            }

            setTimeout(() => {
              uni.redirectTo({
                url: `/pages/lookPrice/lookPrice?item=${encodeURIComponent(JSON.stringify(this.goodsDetail))}&brokerage=${this.brokerage}&freightMoney=${this.freightMoney}&isPrice=${true}`
              });
              this.isClick = false;
            }, 1500)
          } else {
            uni.showToast({
              icon: 'none',
              title: this.$t("bidBuy.hint6"),
              duration: 1500
            })
          }
        }
      }

      if (this.current == 1) {
        console.log(this.goodsDetail);
        uni.navigateTo({
          url: `/pages/confirmGoodsOrder/confirmGoodsOrder?item=${encodeURIComponent(JSON.stringify(this.goodsDetail))}&brokerage=${this.brokerage}&freightMoney=${this.freightMoney}`
        })
      }
    },
    initCountDown() {
      this.tempTime = Number(new Date(this.goodsDetail.auctionTime)).valueOf() - Number(this.nowTime);

      this.timer = setInterval(() => {
        if(this.tempTime <= 1000) {
          clearInterval(this.timer);
          this.timer = null;
        }
        this.d = parseInt(this.tempTime/1000/60/60/24);
        this.h = parseInt(this.tempTime/1000/60/60%24) < 10?"0" + parseInt(this.tempTime/1000/60/60%24):parseInt(this.tempTime/1000/60/60%24);
        this.m = parseInt(this.tempTime/1000/60%60) < 10?"0" + parseInt(this.tempTime/1000/60%60):parseInt(this.tempTime/1000/60%60);
        this.s = parseInt(this.tempTime/1000%60) < 10?"0" + parseInt(this.tempTime/1000%60):parseInt(this.tempTime/1000%60);
        this.tempTime -= 1000;
        // console.log(this.d,this.h,this.m,this.s);
      }, 1000)
    },
    async initFreightMoney() {
      const res = await getFreightMoney(this.goodsDetail.freightId || 1);
      console.log(res);
      this.freightMoney = res.data.money;
    },
    async initServiceChange() {
      const res = await getAboutUs();
      let temp = res.data.companyBrokerage < 10 ? "0" + res.data.companyBrokerage : res.data
          .companyBrokerage;
      temp = "0." + temp
      let tempMoney = String(this.goodsDetail.money).split(".").length > 1 ? this.goodsDetail.money : this
          .goodsDetail.money + ".00";

      this.brokerage = this.accMul(tempMoney, temp);
    },
    accMul(arg1, arg2) {
      var m = 0,
          s1 = arg1.toString(),
          s2 = arg2.toString();
      try {
        m += s1.split(".")[1].length
      } catch (e) {}
      try {
        m += s2.split(".")[1].length
      } catch (e) {}
      return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
    },

    async initBidName() {
      const res = await getBid({commodityId: this.goodsDetail.id});
      if(res.code == 200) {
        const filterBid = res.rows.filter(item => item.userId == uni.getStorageSync("userId"));
        if(filterBid.length > 0) {
          this.totalPrice = filterBid[0].bid;
          this.bidName = this.$t("bidBuy.confirmChange");
        } else {
          this.bidName = this.$t("bidBuy.confirm");
        }
      }
    }
  },
  onLoad(option) {
    this.current = option.current;
    if(option.series) {
      this.series = JSON.parse(decodeURIComponent(option.series));
    }

    if(option.filterBrand) {
      this.filterBrand = JSON.parse(decodeURIComponent(option.filterBrand));
    }

    if(option.condition) {
      this.condition = JSON.parse(decodeURIComponent(option.condition));
    }

    if(option.addr) {
      this.addr = JSON.parse(decodeURIComponent(option.addr));
    }

    this.id = option.id;
    this.goodsDetail = JSON.parse(decodeURIComponent(option.item));
    this.bidmin = this.goodsDetail.money * 0.85
    this.initBidName();
    this.initCountDown();
    this.initFreightMoney();
    this.initServiceChange();
    this.$nextTick(function() {
      uni.pageScrollTo({
        scrollTop: 999999999,
        duration: 0,
        selector: ".bidBuy-view",
        fail(res) {
          console.log(res);
        },
        success(res) {
          console.log(res);
        }
      });
    });
    console.log(this.goodsDetail,"0-0-0-");
  },
  onReady() {
    uni.setNavigationBarTitle({ title: this.$t("bidBuy.title")});
  },
  onUnload() {
    clearInterval(this.timer);
    this.timer = null;
  }
}
</script>

<style lang="scss" scoped>
.bidBuy-view {
  background-color: #FBFBFB;
}

.show-price {
  margin-left: 30rpx;
  margin-top: 20rpx;
  display: flex;
  align-items: center;

  .show-price-desc {
    color: #858585;
    font-family: PingFang SC;
    font-weight: bold;
    font-size: 40rpx;
  }

  .show-price-bid {
    color: #FF0000;
    font-family: PingFang SC;
    font-weight: bold;
    font-size: 50rpx;
  }
}

.goods-img {
  image {
    width: 100%;
    height: 386rpx;
  }
}

.no-margin {
  margin: 0 !important;
}

.layout {
  margin: 0rpx 24rpx;
  padding-bottom: 112rpx;
}

.search {
  padding: 14rpx 22rpx
}

.font-col {
  color: #858585;
}

.indicator {
  @include flex(row);
  justify-content: center;

  &__dot {
    height: 6px;
    width: 6px;
    border-radius: 100px;
    background-color: rgba(255, 255, 255, 0.35);
    transition: background-color 0.3s;

    &--active {
      background-color: #ffffff;
    }
  }
}

.indicator-num {
  border-radius: 40rpx;
  background: #D9D9D97F;
  padding: 4rpx 0;
  height: 36rpx;
  width: 116rpx;
  @include flex;
  justify-content: center;

  &__text {
    color: #FFFFFF;
    font-size: 24rpx;
    font-weight: bold;
  }
}

@mixin bg {
  border-radius: 20rpx;
  background: #FFFFFF;
  box-shadow: 0rpx -2rpx 16rpx 0rpx #00000019;
  margin-top: 20rpx;
}

.price {
  font-family: PingFang SC;
  font-weight: bold;
  padding: 32rpx 24rpx;

  @include bg;
  .title {
    margin-bottom: 18rpx;
    color: #000000;
    font-size: 30rpx;

  }

  .price-num {
    .price-num-b {
      color: #FF0000;
      font-size: 36rpx;
    }

    .price-num-s {
      margin-left: 36rpx;
      color: #FF0000;
      font-size: 20rpx;
    }

    .name {
      color: #000000;
      font-size: 30rpx;
    }
  }
}

.status {

  @include bg ;
  display: flex;
  align-items: center;
  padding: 26rpx 134rpx;
  color: #000000;
  font-family: PingFang SC;
  font-weight: bold;
  font-size: 30rpx;

  .condition {}

  .abrasion {
    margin-left: 104rpx;
  }
}

.commodity-info {
  font-family: PingFang SC;
  font-weight: bold;
  padding: 24rpx 42rpx;
  text-transform: uppercase;

  @include bg;

  .titleGoods {
    color: #000000;
    font-size: 30rpx;
    padding: 24rpx 0;
  }

  .commodity-text {

    display: flex;
    flex-direction: column;
    color: #000;
    font-size: 24rpx;

    .lh {
      // margin-right: 30rpx;
      line-height: 50rpx;
      letter-spacing: 2rpx;

      .bd {
        color: #858585;
      }
    }

    .ls {
      margin-right: 30rpx;
      line-height: 50rpx;
      letter-spacing: 2rpx;

      .bd {
        color: #858585;
      }
    }

    .plaWid {
      // width: 200rpx;
      // text-overflow: ellipsis;
      // white-space: nowrap;
      // overflow: hidden;
      margin-right: 20rpx;
    }
  }
}

.btn {
  width: 100%;
  display: flex;
  position: fixed;
  height: 112rpx;
  bottom: 0;
  font-family: PingFang SC;
  font-weight: bold;
  font-size: 32rpx;
  border-radius: 0rpx;
  text-align: center;
  line-height: 112rpx;

  .toggleCart {
    background: #F1F1F1;
    width: 50%;
    color: #858585;
  }

  .toggleBuy {
    width: 50%;
    background: #000000;
    color: #FFFFFF;

  }
}

.bid-buy {
  margin: 40rpx 0;
  height: 108rpx;
  background-color: #f1f1f1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-radius: 40rpx;
  box-shadow: 0rpx -2rpx 16rpx 0rpx #00000019;

  .bid-buy-btn {
    text-align: center;
    line-height: 108rpx;
    color: #858585;
    font-family: PingFang SC;
    font-weight: bold;
    font-size: 36rpx;
    flex: 1;
    border-radius: 40rpx;
  }

  .common {
    background-color: #fff;
  }
}

.price-corr {
  position: relative;
  margin-top: 20rpx;
  // box-sizing: border-box;

  input {
    border-radius: 20rpx;
    background: #FFFFFF;
    border: 2rpx solid #80808019;
    padding-left: 124rpx;
    box-sizing: border-box;
    height: 94rpx;
  }

  .pla {
    position: absolute;
    top: 8rpx;
    left: 60rpx;
    color: #FAAD67;
    font-family: PingFang SC;
    font-weight: bold;
    font-size: 50rpx;
    text-align: center;
  }

  .hint {
    margin-top: 20rpx;
    color: #858585;
    font-family: PingFang SC;
    font-weight: bold;
    font-size: 36rpx;
    text-align: center;
  }
}

.downTime {
  margin: 15rpx 0;
  color: #858585;
  font-family: PingFang SC;
  font-weight: bold;
  font-size: 36rpx;
  text-align: center;
}

.total-price {
  margin-top: 80rpx;
  text-align: right;

  .total {
    color: #858585;
    font-family: PingFang SC;
    font-weight: bold;
    font-size: 24rpx;
    margin-right: 30rpx;
  }

  .t-price {
    color: #FF0000;
    font-family: PingFang SC;
    font-weight: bold;
    font-size: 50rpx;
  }
}

.rule {
  @include bg;
  margin-top: 20rpx;
  color: #858585;
  font-family: PingFang SC;
  font-weight: bold;
  font-size: 24rpx;
  box-sizing: border-box;
  padding: 38rpx 36rpx;
}

.pla-view {
  height: 45rpx;
  opacity: 1;
}

.hintbew{
  text-align: center;
  font-size: 0.8rem;
  color: red;
  font-weight: 550;
}
.now-buy {
  @include bg;
  padding: 40rpx;

  .buy-hint {
    padding-bottom: 38rpx;
    text-align: center;
    color: #858585;
    font-family: PingFang SC;
    font-weight: bold;
    font-size: 24rpx;
    border-bottom: 2rpx dashed #858585;
  }

  .common-desc {
    color: #858585;
    font-family: PingFang SC;
    font-weight: bold;
    font-size: 24rpx;
  }

  .goods-price {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin: 30rpx 0;

    .price-g {
      color: #FF0000;
      font-family: PingFang SC;
      font-weight: bold;
      font-size: 50rpx;
    }
  }
}
</style>
